<?php

namespace Biz\service\wiki;


use Biz\model\brand\Brand;
use Biz\model\brand\BrandContentKeywords;
use Biz\model\brand\BrandSelectedRecord;
use Biz\model\brand\Content as mBrandContent;
use Biz\model\brand\ContentWiki;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\service\brand\SearchSchedule;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Doraemon\cache\AnswerCounter;
use Doraemon\cache\ArticleCounter;
use Doraemon\cache\BlankCounter;
use Doraemon\cache\PhotoCounter;
use Doraemon\model\Elasticsearch\brandContent\BrandContentEs;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\Brand\BrandContentSearch;
use Doraemon\service\Content\AdmContent;
use Doraemon\service\Format\Blank\HandleBlank;
use Doraemon\service\Format\Note\HandleNote;
use Doraemon\service\Like as sLike;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Link;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\Log;

/**
 * Class WikiContent
 * @package Biz\service\wiki
 */
class WikiContent
{
    const TAB_ALL = 1;
    const TAB_SELECTED = 2;
    const TAB_CANCEL = 3;
    const TAB_TOP = 4;//置顶的内容

    const OBJ_TYPE = [
        1 => '图片',
        2 => '视频',
        3 => '文章',
        4 => '整屋案例',
    ];

    const OWNER_TYPE = [
        1 => '住友',
        2 => '品牌名称'
    ];

    public const FILTER_UIDS = [11941, 6587838, 12456042];//好好住官号、品牌小秘书、好好住福利官

    protected static $debug = false;

    public static function debug()
    {
        self::$debug = true;
        return self::class;
    }

    public static function contentPreView($obj_id)
    {
        $obj_type = \Doraemon\pockets\IdSender\IdSender::getType($obj_id);
        $url = '';
        if ($obj_type == 0) {
            $url = HhzEnv::communityDomain() . "community/note-share/detail?note_id={$obj_id}&preview=1";
        } else {
            if ($obj_type == 1) {
                $url = HhzEnv::communityDomain() . "community/article/detail?article_id={$obj_id}&preview=1";
            } else {
                if ($obj_type == 5) {
                    $url = HhzEnv::communityDomain() . "community/blank/detail?blank_id={$obj_id}&in=1";
                }
            }
        }
        return $url;
    }

    public static function generateLink($obj_id)
    {
        $obj_type = \Doraemon\pockets\IdSender\IdSender::getType($obj_id);
        $link = '';
        if ($obj_type == 0 || $obj_type == 4) {
            $link = LinkFormat::generateSingleLink(LinkConf::LINK_PHOTO, ['note_id' => $obj_id]);
        } else {
            if ($obj_type == 1) {
                $link = LinkFormat::generateSingleLink(LinkConf::LINK_ARTICLE, ['article_id' => $obj_id]);
            } else {
                if ($obj_type == 5) {
                    $link = LinkFormat::generateSingleLink(LinkConf::LINK_BLANK, ['blank_id' => $obj_id]);
                }
            }
        }
        return $link;
    }

    /**
     * 后台审核列表
     * @param $condition
     * @param $page
     * @param $page_size
     * @return array
     */
    public static function admPagedList($condition, $page, $page_size)
    {
        //es搜索条件构造
        $esCondition = [
            'page' => $page,
            'page_size' => $page_size,
            'desc' => 'asc',
            'claim_type' => [1, 3, 4],
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
            'filter_audit_status' => [
                mBrandContent::AUDIT_STATUS_SUCCESS,
                mBrandContent::AUDIT_STATUS_AUTO,
            ],
        ];
        if (!empty($condition['brand_id'])) {
            $esCondition['brand_id'] = $condition['brand_id'];
        }
        if (!empty($condition['obj_type'])) {
            $esCondition['obj_type'] = [$condition['obj_type']];
        }
        if (!empty($condition['claim_type'])) {
            $esCondition['claim_type'] = [$condition['claim_type']];
        }
        if (isset($condition['audit_status']) && $condition['audit_status'] !== '') {
            $esCondition['filter_audit_status'] = array_diff(mBrandContent::ALL_AUDIT_STATUS,
                [$condition['audit_status']]);
        }

        if (isset($condition['search_keywords']) && !empty($condition['search_keywords'])) {
            $esCondition['search_keywords'] = $condition['search_keywords'];
        }

        //es搜索内容列表
        $info = \Doraemon\model\Elasticsearch\brandContent\BrandContentEs::search($esCondition['brand_id'], $esCondition);
//        $info = SearchSchedule::search(new \Biz\module\Classes\adm\ContentSearch($esCondition));
        $ids = $info['list'] ? array_column($info['list'], 'id') : [];
        $total = $info['total'] ?? 0;
        $is_over = $info['is_over'] ?? 1;

        //查询关联的内容列表
        $list = $ids ? mBrandContent::select('*', ['id' => $ids]) : [];
        $list = empty($list) ? [] : array_column($list, null, 'id');

        $brand_ids = empty($list) ? [] : array_column($list, 'brand_id');
        $brand = empty($brand_ids) ? [] : Brand::select('*', ['id' => $brand_ids]);
        $brand_name = empty($brand) ? [] : array_column($brand, 'brand_name', 'id');
        $brand_type = empty($brand) ? [] : array_column($brand, 'brand_type', 'id');
        $brand_logo = empty($brand) ? [] : array_column($brand, 'logo', 'id');


        foreach ($list as &$v) {
            $obj_type = $v['obj_type'];
            $obj_id = $v['obj_id'];
            $logo = $brand_logo[$v['brand_id']] ?? '';
            $info = AdmContent::get($obj_type, $obj_id);
            $info = $info[$obj_id] ?? [];
            $v['type_desc'] = $info['type_desc'] ?? '';
            $v['brand_name'] = $brand_name[$v['brand_id']] ?? '';
            $v['brand_type'] = $brand_type[$v['brand_id']] ?? '';
            $v['brand_logo'] = $logo ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $logo,
                ImgUrl::IMAGE_SIZE_SQ_PHONE) : \Biz\service\brand\Brand::BRAND_DEFAULT_LOGO;
            $v['info'] = [
                'id' => $obj_id,
                'title' => $info['title'] ?? '',
                'content' => $info['content'] ?? '',
                'cover_pic_url' => $info['cover_pic_url'] ?? '',
            ];
            if (!in_array($v['claim_type'], [mBrandContent::CLAIM_TYPE_CONTENT_ONLY])) {
                //查询关联的wiki
                $wikiWhere = WikiContentValid::waitAuditWikiCondition($v['id']);

                $wiki = \Biz\model\brand\ContentWiki::select('*', $wikiWhere);
                $wiki_ids = empty($wiki) ? [] : array_column($wiki, 'wiki_id');
                $claim_wiki_ids = empty($wiki) ? [] : array_column($wiki, 'claim_wiki_id');
                $wiki_ids = array_merge($wiki_ids, $claim_wiki_ids);
                $wiki_ids = array_flip(array_flip($wiki_ids));
                $wikiInfo = \Biz\model\wiki\Wiki::select('*', ['id' => $wiki_ids]);
                $wikiInfo = empty($wikiInfo) ? [] : array_column($wikiInfo, null, 'id');
                $v['wiki_list'] = array_map(function ($v) use ($wikiInfo) {
                    $v['wiki_info'] = $wikiInfo[$v['wiki_id']] ?? [];
                    $v['claim_wiki_info'] = $wikiInfo[$v['claim_wiki_id']] ?? [];
                    return $v;
                }, $wiki);
            }
        }
///HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?wiki_id=' . $v['id'] . '&no-pc-redirect=true',
        $response = compact('list', 'total', 'is_over');

        return $response;
    }

    /**
     * 设置精选内容
     * @param $id
     * @param $brand_id
     * @param $uid
     * @param $msg
     * @param $alreadySelectedNum
     * @param $key
     * @throws \Exception
     */
    public static function setSelected($id, $brand_id, $uid, $msg, $alreadySelectedNum, $key)
    {
        //检查内容是否可以被精选
        $content = WikiContentValid::selectedContent($id, $brand_id);
        $info = AdmContent::get($content['obj_type'], $content['obj_id']);
        $info = $info[$content['obj_id']] ?? [];

        $can_selected = $content['brand_uid'] > 0 || (($info['type_desc'] ?? '') == '图片') ? 1 : 0;
        if (!$can_selected) {
            throw new \Exception('该内容不可以被精选');
        }
        $data['is_selected'] = mBrandContent::FEATURED_SELECT;
        $data['message'] = $msg;
        $where['id'] = $id;

        $rs = mBrandContent::action(function () use ($brand_id, $uid, $data, $where) {
            //修改内容记录
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('修改内容记录失败');
            }

            $in_data['content_id'] = $where['id'];
            $in_data['brand_id'] = $brand_id;
            $in_data['is_selected'] = $data['is_selected'];
            $in_data['created_at'] = date("Y-m-d H:i:s");
            $rs = BrandSelectedRecord::insertData($in_data);
            if (!$rs) {
                throw new \Exception('添加精选记录失败');
            }
            //添加操作日志
            self::addDebugTrace($brand_id, '', [
                'title' => '设置精选内容',
                'data' => $data,
                'where' => $where,
                'in_data' => $in_data
            ], $uid);
            return true;
        });

        //发送动态
        if ($rs) {
            \Doraemon\service\Dynamic::forwardNote($uid, $content['obj_id'], $msg);
            \Biz\cache\brand\BrandSelected::setItem($key, $alreadySelectedNum + 1);
        }
    }

    /**
     * 取消精选内容
     * @param $id
     * @param $brand_id
     * @param $uid
     */
    public static function cancelSelected($id, $brand_id, $uid)
    {
        //检查内容是否满足条件
        $content = WikiContentValid::cancelSelectedContent($id, $brand_id);
        $data['is_selected'] = mBrandContent::FEATURED_NONE;
        $where['id'] = $id;

        $rs = mBrandContent::action(function () use ($brand_id, $uid, $data, $where) {
            //修改内容记录
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('修改内容记录失败');
            }
            //添加操作日志
            self::addDebugTrace($brand_id, [
                'title' => '取消精选内容',
                'data' => $data,
                'where' => $where
            ], $uid);

            return true;
        });

        if ($rs) {
            \Doraemon\service\Dynamic::delOneByObjIdUid($content['obj_id'], $uid,
                \Doraemon\pockets\constInterface\Feed::FORWARD_PHOTO);
        }

    }


    /**
     * 重新收录内容
     * @param $id
     * @param $brand_id
     * @param $uid
     */
    public static function reclaim($id, $brand_id, $uid)
    {
        //检查内容是否满足条件
        WikiContentValid::reclaimContent($id, $brand_id);

        $data = [
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
        ];

        $where = [
            'id' => $id,
        ];

        mBrandContent::action(function () use ($brand_id, $uid, $data, $where) {
            //修改内容记录
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('修改内容记录失败');
            }

            //添加操作日志
            self::addDebugTrace($brand_id, '', [
                'title' => '重新收录内容',
                'data' => $data,
                'where' => $where
            ], $uid);
        });
    }

    /**
     * 审核通过
     * @param $id int 内容记录id
     * @param int $wid
     * @param int $adminId
     * @throws \Exception
     */
    public static function audit($id, $wid = 0, $adminId = 0)
    {
        //检查内容是否存在
        $content = mBrandContent::get('*', [
            'id' => $id,
        ]);

        if (!$content) {
            throw new \Exception('操作的内容不存在,id:' . $id);
        }
        if ($content['claim_type'] == mBrandContent::CLAIM_TYPE_NONE) {
            throw new \Exception('操作的内容状态已经变更');
        }

        /**
         * 仅认领内容 -> 所关联内容需从该品牌的内容列表中抹除
         * 认领商品 -> 该商品及内容重新回到品牌商的「待认领」列表
         * 仅关联商品 -> 撤销关联商品的操作
         * 认领内容并关联商品 -> 1.标记为「内容不属于该品牌」的则流程结束（后续该内容不得出现在品牌商待认领列表）
         * 2.未标记「内容不属于该品牌」的则该内容重新回到品牌商的「已收录」列表
         */
        switch ($content['claim_type']) {
            case mBrandContent::CLAIM_TYPE_CONTENT_ONLY:
                $data = [
                    'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
                    'content_status' => mBrandContent::CLAIM_MATCH,
                    'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
                    'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                ];
                $where = [
                    'id' => $id,
                ];

                $rs = mBrandContent::update($data, $where)->rowCount();
                if (!$rs) {
                    throw new \Exception('更新审核状态失败');
                }
                break;
            case mBrandContent::CLAIM_TYPE_WIKI_ONLY:
                self::auditWikiOnly($id, $wid, $content, $adminId);
                break;
            case mBrandContent::CLAIM_TYPE_APPEND_ONLY:
                self::auditAppendOnly($id, $wid, $content);
                break;
            case mBrandContent::CLAIM_TYPE_BOTH:
                self::auditBoth($id, $wid, $content, $adminId);
                break;
            default:
                throw new \Exception('未开发的审核类型');
                break;
        }

        //发送下行
        $uid = Brand::get('uid', ['id' => $content['brand_id']]);
        self::sendMsg($uid, $message = '你的认领/关联操作已通过审核并已生效', $content['obj_id']);

        //发送站内消息
        \Biz\service\BrandIndex::writeMsg(
            $content['brand_id'],
            \Biz\model\brandIndex\BrandMsg::MSG_TYPE_PASS,
            \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_CONTENT,
            $message,
            $content['obj_type'],
            $content['obj_id']
        );

        $title = '审核通过';
        self::addDebugTrace(0, $content['obj_id'], compact('title', 'id', 'message'), 0, $adminId);
    }

    /**
     * 审核不通过
     * @param $id int 内容记录id
     * @param $wid int 商品记录id
     * @param $message
     * @param $contentSign int 后台标记「内容不属于该品牌
     * @param $adminId
     * @throws \Exception
     */
    public static function auditReject($id, $wid, $message, $contentSign, $adminId)
    {

        if (strlen($message) == 0) {
            throw new \Exception('必需补充不通过的原因');
        }

        //检查内容是否存在
        $content = mBrandContent::get('*', [
            'id' => $id,
        ]);

        if (!$content) {
            throw new \Exception('操作的内容不存在,id:' . $id);
        }
        if ($content['claim_type'] == mBrandContent::CLAIM_TYPE_NONE) {
            throw new \Exception('操作的内容状态已经变更');
        }

        /**
         * 仅认领内容 -> 所关联内容需从该品牌的内容列表中抹除
         * 认领商品 -> 该商品及内容重新回到品牌商的「待认领」列表
         * 仅关联商品 -> 撤销关联商品的操作
         * 认领内容并关联商品 -> 1.标记为「内容不属于该品牌」的则流程结束（后续该内容不得出现在品牌商待认领列表）
         * 2.未标记「内容不属于该品牌」的则该内容重新回到品牌商的「已收录」列表
         */
        switch ($content['claim_type']) {
            case mBrandContent::CLAIM_TYPE_CONTENT_ONLY:
                $rs = mBrandContent::update([
                    'audit_status' => mBrandContent::AUDIT_STATUS_REJECT,
                    'reject_reason' => $message,
                    'claim_content_status' => mBrandContent::CLAIM_CONTENT_NONE,
                ], ['id' => $id])->rowCount();
                if (!$rs) {
                    throw new \Exception('更新审核状态失败');
                }
                break;
            case mBrandContent::CLAIM_TYPE_WIKI_ONLY:
                self::auditRejectWikiOnly($id, $wid, $message, $content);
                break;
            case mBrandContent::CLAIM_TYPE_APPEND_ONLY:
                self::auditRejectAppendOnly($id, $wid, $message, $content);
                break;
            case mBrandContent::CLAIM_TYPE_BOTH:
                self::auditRejectBoth($id, $wid, $message, $content, $contentSign);
                break;
        }

        //发送下行
        $uid = Brand::get('uid', ['id' => $content['brand_id']]);
        self::sendMsg($uid, $message, $content['obj_id']);

        //发送站内消息
        \Biz\service\BrandIndex::writeMsg(
            $content['brand_id'],
            \Biz\model\brandIndex\BrandMsg::MSG_TYPE_OVER,
            \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_CONTENT,
            $message,
            $content['obj_type'],
            $content['obj_id']
        );

        $title = '审核不通过';
        self::addDebugTrace(0, $content['obj_id'], compact('title', 'id', 'message'), 0, $adminId);
    }

    /**
     * 审核后,仅认领商品
     * @param $id
     * @param $wid
     * @param $content
     * @param $adminId
     * @throws \Exception
     */
    public static function auditWikiOnly($id, $wid, $content, $adminId)
    {
        //查询待认领商品的数量
        $wikiWhere = WikiContentValid::waitAuditWikiCondition($id);
        $count = \Biz\model\brand\ContentWiki::count($wikiWhere);
        $wiki = \Biz\model\brand\ContentWiki::get('*', ['id' => $wid]);

        $rs = \Biz\model\brand\ContentWiki::action(function () use ($wid, $count, $id, $content, $wiki) {
            //修改审核状态
            \Biz\model\brand\ContentWiki::update([
                'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                'reject_reason' => '',
            ], ['id' => $wid]);

            if (($content['match_status'] & mBrandContent::MATCH_BRAND_WIKI) == 0) {
                mBrandContent::update(['match_status' => $content['match_status'] | mBrandContent::MATCH_BRAND_WIKI],
                    ['id' => $id]);
            }

            if ($count > 1) { //还能继续审核,保持锁定状态

            } else {//解除锁定
                $tempUpData = [
                    'match_status' => $content['match_status'] & ~mBrandContent::MATCH_WIKI_TITLE,
                    'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                    'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
                ];
                mBrandContent::update($tempUpData, ['id' => $id]);
            }

            $brand_id = $content['brand_id'];

            //查询绑定wiki的basic_id
            $basicId = \Biz\model\wiki\Wiki::get('basic_id', ['id' => $wiki['claim_wiki_id']]);

            //添加wiki的关联关系
            $rs = WikiBasic::setBrandWikiBasic($brand_id, $wiki['wiki_id'], $basicId);

            if (!$rs) {
                throw new \Exception('商品已经被认领');
            }

            return $rs;
        });


        if ($rs) {
            //认领拥有相同wiki的待认领内容
            self::afterClaimWiki($content['brand_id'], $adminId, $wiki['wiki_id'], [$wiki['claim_wiki_id']],
                $wiki['id']);
        }

    }

    /**
     * 审核后,仅追加商品
     * @param $id
     * @param $content
     * @param $wid
     * @throws \Exception
     */
    public static function auditAppendOnly($id, $wid, $content)
    {
        //查询待认领商品的数量
        $wikiWhere = WikiContentValid::waitAuditWikiCondition($id);
        $count = \Biz\model\brand\ContentWiki::count($wikiWhere);

        //修改审核状态
        \Biz\model\brand\ContentWiki::update([
            'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
            'reject_reason' => '',
        ], ['id' => $wid]);

        if ($count > 1) { //还能继续审核,保持锁定状态

        } else {//解除锁定
            $tempUpData = [
                'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
            ];
            mBrandContent::update($tempUpData, ['id' => $id]);
        }

        $obj_type = $content['obj_type'];
        $obj_id = $content['obj_id'];

        $wikiType = [
            0 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_NOTE,
            1 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_ARTICLE,
            5 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_BLANK,
        ];

        //查询内容关联的wiki
        $wiki = ObjRelateWiki::getRelateListByObjIds($wikiType[$obj_type], [$obj_id]);
        $wiki = empty($wiki) ? [] : $wiki[$obj_id];
        $wiki_ids = empty($wiki) ? [] : array_column($wiki, 'wiki_id');

        //查询已有的wiki id
        $wikiWhere = [
            'cid' => $content['id'],
            'relation' => [
                \Biz\model\brand\ContentWiki::RELATION_DONE,
            ],
        ];
        $wiki_id = \Biz\model\brand\ContentWiki::select('wiki_id', $wikiWhere);
        if (empty($wiki_id)) {
            return;
        }
        $wiki_id = array_merge($wiki_ids, $wiki_id);

        $info = AdmContent::get($obj_type, $obj_id);
        $info = $info[$obj_id] ?? [];
        $obj_uid = $info['uid'] ?? 0;
        //追加的商品,添加内容与wiki的关联关系
        $temp_obj_uid = $obj_uid;//$obj_uid
        switch ($obj_type) {
            case 0:
                \Biz\module\Classes\wiki\RelateWiki::objRelateWiki(
                    $temp_obj_uid,
                    $obj_id,
                    \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_NOTE,
                    '',
                    0,
                    $wiki_id,
                    \Biz\model\wiki\ObjRelateWiki::TYPE_BRAND_REL
                );
                break;
            case 1:
                \Biz\module\Classes\wiki\RelateWiki::objRelateWiki(
                    $temp_obj_uid,
                    $obj_id,
                    \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_ARTICLE,
                    '',
                    0,
                    $wiki_id,
                    \Biz\model\wiki\ObjRelateWiki::TYPE_BRAND_REL
                );
                break;
            case 5:
                ObjRelateWiki::blankRelateWiki($temp_obj_uid, $obj_id, $wiki_id,
                    \Biz\model\wiki\ObjRelateWiki::TYPE_BRAND_REL);
                break;
        }
    }

    /**
     * 审核后,认领内容并关联商品
     * @param $id
     * @param $wid
     * @param $content
     * @param $adminId
     * @throws \Exception
     */
    public static function auditBoth($id, $wid, $content, $adminId)
    {
        self::auditAppendOnly($id, $wid, $content);
    }

    public static function auditRejectWikiOnly($id, $wid, $message, $content)
    {
        //查询待认领商品的数量
        $wikiWhere = WikiContentValid::waitAuditWikiCondition($id);
        $count = \Biz\model\brand\ContentWiki::count($wikiWhere);

        //返回之前的认领状态
        \Biz\model\brand\ContentWiki::update([
            'relation' => \Biz\model\brand\ContentWiki::RELATION_MATCH,
            'claim_wiki_id' => 0,
            'audit_status' => mBrandContent::AUDIT_STATUS_REJECT,
            'reject_reason' => $message,
        ], ['id' => $wid]);

        if ($count > 1) { //还能继续审核,保持锁定状态
            mBrandContent::update([
                'wiki_num[-]' => 1,
                'wiki_status[+]' => 1,
            ], ['id' => $id]);
        } else {
            //解除锁定
            $tempUpData = [
                'wiki_num[-]' => 1,
                'wiki_status[+]' => 1,
                'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
                'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
            ];
            //没有认领过内容,没有追加过商品,需要从内容列表中抹除
            if (WikiContentValid::checkClaim($content, 1)) {
                //已经有内容关联或者商品关联
                $tempUpData['audit_status'] = $content['last_audit_status'];
            } else {
                if (WikiContentValid::checkMatch($content)) {
                    //恢复初始匹配状态
                    $tempUpData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_MATCH;
                } else {
                    $tempUpData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_NONE;
                }
            }
            mBrandContent::update($tempUpData, ['id' => $id]);
        }
    }

    public static function auditRejectAppendOnly($id, $wid, $message, $content)
    {
        //查询待认领商品的数量
        $wikiWhere = WikiContentValid::waitAuditWikiCondition($id);
        $count = \Biz\model\brand\ContentWiki::count($wikiWhere);

        //撤回追加操作
        \Biz\model\brand\ContentWiki::update([
            'relation' => \Biz\model\brand\ContentWiki::RELATION_NONE,
            'claim_wiki_id' => 0,
            'audit_status' => mBrandContent::AUDIT_STATUS_REJECT,
            'reject_reason' => $message,
        ], ['id' => $wid]);

        if ($count > 1) { //还能继续审核,保持锁定状态
            mBrandContent::update([
                'wiki_num[-]' => 1,
            ], ['id' => $id]);
        } else {
            //解除锁定
            $tempUpData = [
                'wiki_num[-]' => 1,
                'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
                'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
            ];
            //认领状态判断
            if (WikiContentValid::checkClaim($content, 1)) {
                //已经有内容关联或者商品关联
                $tempUpData['audit_status'] = $content['last_audit_status'];
            } else {
                if (WikiContentValid::checkMatch($content)) {
                    //恢复初始匹配状态
                    $tempUpData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_MATCH;
                } else {
                    $tempUpData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_NONE;
                }
            }
            mBrandContent::update($tempUpData, ['id' => $id]);
        }
    }

    public static function auditRejectBoth($id, $wid, $message, $content, $contentSign)
    {
        //查询待认领商品的数量
        $wikiWhere = WikiContentValid::waitAuditWikiCondition($id);
        $count = \Biz\model\brand\ContentWiki::count($wikiWhere);

        //撤回追加商品操作
        \Biz\model\brand\ContentWiki::update([
            'relation' => \Biz\model\brand\ContentWiki::RELATION_NONE,
            'claim_wiki_id' => 0,
            'audit_status' => mBrandContent::AUDIT_STATUS_REJECT,
            'reject_reason' => $message,
        ], ['id' => $wid]);

        if ($count > 1) { //还能继续审核,保持锁定状态
            $tempUpData = [
                'wiki_num[-]' => 1,
            ];
            if ($contentSign > 0) {
                $tempUpData['content_status'] = mBrandContent::CLAIM_NONE_MATCH;
            }
            mBrandContent::update($tempUpData, ['id' => $id]);
        } else {
            //解除锁定
            $tempUpData = [
                'wiki_num[-]' => 1,
                'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
                'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
            ];
            if ($contentSign > 0) {
                $tempUpData['content_status'] = mBrandContent::CLAIM_NONE_MATCH;
            }

            if (WikiContentValid::checkClaim($content, 1)) {
                //已经有内容关联或者商品关联
                $tempUpData['audit_status'] = $content['last_audit_status'] ?: mBrandContent::AUDIT_STATUS_SUCCESS;
            } else {
                if ($contentSign > 0) {
                    //标记为「内容不属于该品牌」的则流程结束（后续该内容不得出现在品牌商待认领列表）
                    $tempUpData['claim_content_status'] = $content['wiki_status'] > 0 ? mBrandContent::CLAIM_CONTENT_MATCH : mBrandContent::CLAIM_CONTENT_NONE;
                } else {
                    //未标记「内容不属于该品牌」的则该内容重新回到品牌商的「已收录」列表
                    $tempUpData['audit_status'] = mBrandContent::AUDIT_STATUS_SUCCESS;
                }
            }

            mBrandContent::update($tempUpData, ['id' => $id]);
        }
    }

    /**
     * 认领商品,追加关联商品
     * @param $flag
     * @param $id
     * @param $wid
     * @param $claim_wiki_id
     * @param $brand_id
     * @param $uid
     * @param $rightsName
     * @throws \Exception
     */
    public static function claimWiki($flag, $id, $wid, $claim_wiki_id, $brand_id, $uid, $rightsName)
    {
        //参数校验
        $claim_wiki_id = explode(",", $claim_wiki_id);
        $claim_wiki_id = array_filter($claim_wiki_id);
        if (empty($claim_wiki_id)) {
            throw new \Exception('未选择商品');
        }

        //检查内容是否满足条件
        $content = WikiContentValid::claimWikiContent($id, $brand_id);
        if ($content['claim_type'] != mBrandContent::CLAIM_TYPE_NONE) {
            //认领商品追加例外
            $except1 = $content['claim_type'] == mBrandContent::CLAIM_TYPE_WIKI_ONLY && $flag == 1;
            $except2 = $content['claim_type'] == mBrandContent::CLAIM_TYPE_APPEND_ONLY && $flag == 2;

            if (!$except1 && !$except2) {
                throw new \Exception('正在审核中');
            }
        }

        switch ($flag) {
            case 1: //认领商品
                //检查商品是否满足条件
                $wiki = WikiContentValid::claimWiki($wid, $brand_id);

                $data = [
                    'relation' => \Biz\model\brand\ContentWiki::RELATION_DONE,
                    'claim_wiki_id' => current($claim_wiki_id),
                    'operation_mode' => $wiki['operation_mode'] | \Biz\model\brand\ContentWiki::OPERATION_MODE_CLAIM,
                    'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
                ];

                $where = [
                    'id' => $wiki['id'],
                ];

                //检查商品是否已经被认领
                $info = \Biz\model\wiki\Wiki::getByWhere(['id' => $wiki['wiki_id']]);
                if ($info['brand_id'] && $info['brand_id'] != $brand_id) {
                    throw new \Exception('认领商品失败,商品已经被其他品牌认领');
                }

                mBrandContent::action(function () use (
                    $brand_id,
                    $data,
                    $where,
                    $uid,
                    $content,
                    $claim_wiki_id,
                    $wiki
                ) {
                    //修改关联wiki的状态
                    $rs = \Biz\model\brand\ContentWiki::update($data, $where)->rowCount();
                    if (!$rs) {
                        throw new \Exception('认领商品失败');
                    }

                    //待认领商品数量-1,认领商品+1 内容认领状态变更
                    $contentData = [
                        'wiki_num[+]' => 1,
                        'wiki_status[-]' => 1,
                        'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
                        'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
                        'claim_type' => mBrandContent::CLAIM_TYPE_WIKI_ONLY,
                        'last_audit_status' => $content['audit_status'],
                    ];
                    if (strtotime($content['claim_time']) <= 0) {
                        $contentData['claim_time'] = date("Y-m-d H:i:s");
                    }
                    if ($content['first_claim_time'] == '0000-00-00 00:00:00') {
                        $contentData['first_claim_time'] = date("Y-m-d H:i:s");
                    }

                    $rs = mBrandContent::update($contentData, ['id' => $content['id']])->rowCount();
                    if (!$rs) {
                        throw new \Exception('更新待认领商品数量失败');
                    }

                    //添加操作日志
                    $title = '商品认领';
                    self::addDebugTrace($brand_id, $content['obj_id'], compact('title', 'data', 'where', 'contentData'),
                        $uid);
                });

                //认领拥有相同wiki的待认领内容
//                self::afterClaimWiki($brand_id, $uid, $wiki['wiki_id'], $claim_wiki_id, $wiki['id']);

                break;
            case 2: //追加商品::仅关联商品
                self::extendWiki($brand_id, $uid, $claim_wiki_id, $content);
                break;
            case 3: //追加商品::认领内容并关联商品
                self::extendWiki($brand_id, $uid, $claim_wiki_id, $content, $plus = true);
                break;
        }
        return $content;
    }

    public static function afterClaimWiki($brand_id, $uid, $wiki_id, $claim_wiki_id, $id)
    {
        //查询拥有相同商品的关联
        $searchCondition = [
            'brand_id' => $brand_id,
            'wiki_id' => $wiki_id,
            'id[!]' => $id,
            'relation' => \Biz\model\brand\ContentWiki::RELATION_MATCH
        ];
        $list = \Biz\model\brand\ContentWiki::select('*', $searchCondition);
        $cidArr = empty($list) ? [] : array_column($list, 'cid');
        if (empty($cidArr)) {
            return;
        }

        //根据商品关联查询内容关联状态
        $contentArr = mBrandContent::select('*', [
            'brand_id' => $brand_id,
            'claim_content_status' => [
                mBrandContent::CLAIM_CONTENT_MATCH,
                mBrandContent::CLAIM_CONTENT_DONE,
            ],
            'id' => $cidArr,
        ]);
        $contentArr = empty($contentArr) ? [] : array_column($contentArr, null, 'id');

        $claim_wiki_id = current($claim_wiki_id);
        foreach ($list as $wiki) {
            try {
                if (!isset($contentArr[$wiki['cid']])) {
                    continue;
                }

                $content = $contentArr[$wiki['cid']];

                $data = [
                    'relation' => \Biz\model\brand\ContentWiki::RELATION_DONE,
                    'claim_wiki_id' => $claim_wiki_id,
                    'operation_mode' => $wiki['operation_mode'] | \Biz\model\brand\ContentWiki::OPERATION_MODE_CLAIM,
                    'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                    'reject_reason' => '',
                ];

                $where = [
                    'id' => $wiki['id'],
                ];

                //查询已有的wiki id
                $wikiWhere = [
                    'cid' => $content['id'],//'wiki_id', 'claim_wiki_id'
                    'relation' => [
                        \Biz\model\brand\ContentWiki::RELATION_DONE,
                    ],
                    "OR" => [
                        'wiki_id' => $claim_wiki_id,
                        'claim_wiki_id' => $claim_wiki_id,
                    ]
                ];
                $count = \Biz\model\brand\ContentWiki::count($wikiWhere);
                if ($count) {
                    continue;
                }


                //进行认领操作
                mBrandContent::action(function () use ($brand_id, $data, $where, $uid, $content) {

                    //修改关联wiki的状态
                    $rs = \Biz\model\brand\ContentWiki::update($data, $where)->rowCount();
                    if (!$rs) {
                        throw new \Exception('认领商品失败');
                    }

                    //待认领商品数量-1,内容认领状态变更
                    $contentData = [
                        'wiki_num[+]' => 1,
                        'wiki_status[-]' => 1,
                        'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
                    ];
                    if (strtotime($content['claim_time']) <= 0) {
                        $contentData['claim_time'] = date("Y-m-d H:i:s");
                    }


                    //查询待认领商品的数量
                    $wikiWhere = WikiContentValid::waitAuditWikiCondition($content['id']);
                    $count = \Biz\model\brand\ContentWiki::count($wikiWhere);


                    if ($count > 1) { //还能继续审核,保持锁定状态

                    } else {//解除锁定
                        if (in_array($content['claim_type'],
                                [mBrandContent::CLAIM_TYPE_NONE]) && in_array($content['audit_status'],
                                [mBrandContent::AUDIT_STATUS_NONE])) {
                            $contentData += [
                                'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
                            ];
                        }
                    }

                    $rs = mBrandContent::update($contentData, ['id' => $content['id']])->rowCount();
                    if (!$rs) {
                        throw new \Exception('更新待认领商品数量失败');
                    }

                    //添加操作日志
                    $title = '相同商品的认领';
                    self::addDebugTrace($brand_id, $content['obj_id'], compact('title', 'data', 'where', 'contentData'),
                        $uid);
                });
            } catch (\Exception $e) {
                //错误日志
                $title = '相同商品的认领错误';
                self::addDebugTrace($brand_id, $content['obj_id'], compact('title', 'wiki', 'e'));
            }
        }
    }

    public static function extendWiki($brand_id, $uid, $claim_wiki_id, $content, $plus = false)
    {
        $obj_type = $content['obj_type'];
        $obj_id = $content['obj_id'];

        //检查追加的商品id
        //查询已有的wiki id
        $wikiWhere = [
            'cid' => $content['id'],
            'relation' => [
                \Biz\model\brand\ContentWiki::RELATION_DONE,
            ],
        ];
        $rs = \Biz\model\brand\ContentWiki::select(['wiki_id', 'claim_wiki_id'], $wikiWhere);
        $relation_wiki_ids = empty($rs) ? [] : array_column($rs, 'wiki_id');
        $relation_claim_wiki_ids = empty($rs) ? [] : array_column($rs, 'claim_wiki_id');

        //去掉已经关联的wiki
        foreach ($claim_wiki_id as $k => $v) {
            if (in_array($v, $relation_wiki_ids) || in_array($v, $relation_claim_wiki_ids)) {
                unset($claim_wiki_id[$k]);
            }
        }
        if (empty($claim_wiki_id)) {
            throw new \Exception('选择商品已经存在');
        }


        //内容认领状态变更
        $claim_type = $plus ? mBrandContent::CLAIM_TYPE_BOTH : mBrandContent::CLAIM_TYPE_APPEND_ONLY;

        $contentData = [
            'wiki_num[+]' => count($claim_wiki_id),
            'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
            'claim_type' => $claim_type,
            'last_audit_status' => $content['audit_status'],
        ];

        if ($content['claim_content_status'] != mBrandContent::CLAIM_CONTENT_DONE) {
            $contentData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_DONE;
            if ($plus) {
                $contentData['content_status'] = mBrandContent::CLAIM_MATCH;
            }
            if (strtotime($content['claim_time']) <= 0) {
                $contentData['claim_time'] = date("Y-m-d H:i:s");
            }
            if ($content['first_claim_time'] == '0000-00-00 00:00:00') {
                $contentData['first_claim_time'] = date("Y-m-d H:i:s");
            }
        }
        $rs = mBrandContent::update($contentData, ['id' => $content['id']])->rowCount();
        if (!$rs) {
            throw new \Exception('更新内容认领状态失败');
        }

        $wiki_id = array_merge($relation_wiki_ids, $claim_wiki_id);
        $wiki_id = array_flip(array_flip($wiki_id));

        \Doraemon\tools\Log::position_info("追加wiki", [$content, $wiki_id]);


        foreach ($wiki_id as $v) {
            try {
                //添加内容与wiki的认领关联关系
                WikiContentSync::autoClaimSaveWiki(
                    $brand_id,
                    $brand_uid = $uid,
                    $obj_type,
                    $obj_id,
                    $cid = $content['id'],
                    $v,
                    $wiki_id,
                    '追加商品关联'
                );
            } catch (\Exception $e) {
                \Doraemon\tools\Log::position_info("内容池操作::认领商品,追加关联商品",
                    compact('brand_id', 'brand_uid', 'obj_type', 'obj_id', 'e', 'v'));
            }
        }
    }

    public static function wikiPagedList($brand_id, $id = 0, $word = '', $page = 1, $pageSize = 20)
    {
        //待认领内容数量
        $where = [
            'brand_id' => $brand_id,
            'basic_state' => \Biz\model\wiki\WikiBasic::ADM_ALLOW_STATE
        ];
        if (strlen($word)) {
            $where['OR'] = [
                'title[~]' => $word,
                'id' => $word,
            ];
        }

        $total = \Biz\model\wiki\WikiBasic::count($where);

        $is_over = $page * $pageSize > $total ? 1 : 0;
        $offset = ($page - 1) * $pageSize;
        $offset = $offset > 0 ? $offset : 0;

        $where += [
            'LIMIT' => [
                $offset,
                $pageSize
            ]
        ];
        $list = \Biz\model\wiki\WikiBasic::select('*', $where);

        foreach ($list as $k => $item) {
            $info = \Biz\model\wiki\WikiBasic::formatInfo($item);
            $list[$k]['cover_img'] = $info['cover_img_url'];
        }


        //查询已经关联的商品
        $basicMap = [];
        if ($id > 0) {
            $wikiWhere = [
                'cid' => $id,
                'relation' => [
                    \Biz\model\brand\ContentWiki::RELATION_DONE,
                ],
            ];
            $rs = \Biz\model\brand\ContentWiki::select(['wiki_id', 'claim_wiki_id'], $wikiWhere);
            $rs_wiki = array_column($rs, 'wiki_id');
            $rs_claim_wiki = array_column($rs, 'claim_wiki_id');
            $relation_wiki_ids = array_merge($rs_wiki, $rs_claim_wiki);
            $relation_wiki_ids = array_flip(array_flip($relation_wiki_ids));

            //查询basic_id
            $basicMap = empty($relation_wiki_ids) ? [] : \Biz\model\wiki\Wiki::select([
                'id',
                'basic_id'
            ], ['id' => $relation_wiki_ids]);
            $basicMap = array_column($basicMap, 'basic_id');
        }

        $response = [];
        if ($list) {
            $basic_ids = array_column($list, 'id');
            $where = [
                'brand_id' => $brand_id,
                'is_default' => 1,
                'basic_id' => $basic_ids,
                'status[!]' => \Biz\model\wiki\Wiki::STATUS_DEL,
            ];
            //查询默认的wiki id
            $wikiMap = \Biz\model\wiki\Wiki::select([
                'id',
                'basic_id',
                'title',
                'cover_img'
            ], $where);
            $wikiMap = empty($wikiMap) ? [] : array_column($wikiMap, null, 'basic_id');

            foreach ($list as $v) {
                $temp = $wikiMap[$v['id']] ?? [];
                if ($temp) {
                    $response[] = [
                        'id' => $temp['id'],
                        'basic_id' => $v['id'],
                        'short' => $v['title'],
                        'title' => $temp['title'],
                        'cover_img' => $v['cover_img'] && !empty($v['cover_img']) ? $v['cover_img'] : AdmWiki::formatImg($temp['cover_img']),
                        'relation' => in_array($v['id'], $basicMap) ? 1 : 0,
                    ];
                }
            }
        }

        $list = $response;
        return compact('total', 'list', 'is_over');
    }

    /**
     * 查看已关联商品列表
     * @param $brand_id
     * @param $id
     * @return array
     */
    public static function itemWikiList($brand_id, $id)
    {
        //查询关联的wiki列表
        $wikiWhere = [
            'cid' => $id,
            'brand_id' => $brand_id,
            'relation' => [
                \Biz\model\brand\ContentWiki::RELATION_DONE,
            ],
        ];
        $list = \Biz\model\brand\ContentWiki::select('*', $wikiWhere);

        $wiki_ids = empty($list) ? [] : array_column($list, 'wiki_id');
        $claim_wiki_ids = empty($list) ? [] : array_column($list, 'claim_wiki_id');
        $wiki_ids = array_merge($wiki_ids, $claim_wiki_ids);
        $wiki_ids = array_flip(array_flip($wiki_ids));

        //查询wiki标题和首图
        list('titleMap' => $titleMap, 'imgMap' => $imgMap, 'basicMap' => $basicMap, 'basic_id' => $basic_ids) = self::formatWikiList($wiki_ids);

        $response = [];
        foreach ($list as $v) {
            $temp_wiki_id = $v['claim_wiki_id'] > 0 ? $v['claim_wiki_id'] : $v['wiki_id'];
            $basic_id = $basicMap[$temp_wiki_id] ?? $v['wiki_id'];
            if (in_array($basic_id, $basic_ids)) {
                $response[] = [
                    'id' => $v['wiki_id'],
                    'wid' => $v['id'],
                    'basic_id' => $basic_id,
                    'title' => $titleMap[$temp_wiki_id] ?? '',
                    'cover_img' => $imgMap[$temp_wiki_id] ?? '',
                ];
            }
        }

        return ['list' => $response];
    }

    public static function formatWikiList($wiki_ids)
    {
        //查询basic_id
        $basicMap = empty($wiki_ids) ? [] : \Biz\model\wiki\Wiki::select([
            'id',
            'basic_id'
        ], [
            'id' => $wiki_ids,
            'status[!]' => \Biz\model\wiki\Wiki::STATUS_DEL,
            'basic_id[>]' => 0
        ]);
        $basicMap = array_column($basicMap, 'basic_id', 'id');

        //查询basic_id对应的wiki
        $basic_id = array_values($basicMap);

        //查询basic_id是否下架
        $basic_id = empty($basic_id) ? [] : \Biz\model\wiki\WikiBasic::select('id',
            ['id' => $basic_id, 'basic_state' => \Biz\model\wiki\WikiBasic::ADM_ALLOW_STATE]);

        $basicInfo = empty($basic_id) ? [] : \Biz\model\wiki\Wiki::select('*', ['basic_id' => $basic_id]);
        $basicInfoMap = [];
        if ($basicInfo) {
            foreach ($basicInfo as $v) {
                if ($v['is_default'] == 1) {
                    $basicInfoMap[$v['basic_id']] = $v;
                }
                if (!isset($basicInfoMap[$v['basic_id']])) {
                    $basicInfoMap[$v['basic_id']] = $v;
                }
            }
        }

        $title = empty($wiki_ids) ? [] : \Biz\model\wiki\Wiki::select([
            'id',
            'title',
            'cover_img'
        ], ['id' => $wiki_ids]);
        $titleMap = [];
        $imgMap = [];

        foreach ($title as $v) {
            $id = $v['id'];
            $temp_basic_id = $basicMap[$id] ?? 0;
            $temp_basic_info = $basicInfoMap[$temp_basic_id] ?? [];

            $titleMap[$id] = $temp_basic_info['title'] ?? $v['title'];
            $imgMap[$id] = !empty($temp_basic_info['cover_img']) ? AdmWiki::formatImg($temp_basic_info['cover_img']) : AdmWiki::formatImg($v['cover_img']);
        }
        return compact('titleMap', 'imgMap', 'basicMap', 'basic_id');
    }

    public static function getListForActivity($uid, array $brandIds, $page, int $currentTime)
    {
        //es搜索条件构造
        $esCondition = [
            'brand_ids' => $brandIds,
            'page' => $page,
            'page_size' => 20,
            'is_owner' => false,
            'sort' => 'random',
            'filter_audit_status' => [
                mBrandContent::AUDIT_STATUS_REJECT,
            ],
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
            'current_time' => $currentTime,
            'filter_owner_uid' => [11941, 6587838],
        ];

        //es搜索内容列表
        $info = \Doraemon\model\Elasticsearch\brandContent\BrandContentEs::search(0, $esCondition);
//        $info = SearchSchedule::search(new \Biz\module\Classes\adm\ContentSearch($esCondition));
        $ids = $info['list'] ? array_column($info['list'], 'id') : [];
        $total = $info['total'] ?? 0;
        $is_over = $info['is_over'] ?? 1;

        $formatedList = self::getFormatListByIds($ids, $uid);

        $list = [];
        foreach ($formatedList as $objId => $value) {
            switch ($value['type']) {
                case  BlockType::TYPE_PHOTO:
                    $value['photo']['wiki_list'] = $value['photo']['wiki_list'] ?? [];
                    $value['action_info'] = [
                        'type' => 11,
                        'addtime' => $value['photo']['photo_info']['addtime']
                    ];
                    break;
                case  BlockType::TYPE_BLANK:
                    $value['blank']['wiki_list'] = $value['blank']['wiki_list'] ?? [];
                    $value['action_info'] = [
                        'type' => 11,
                        'addtime' => $value['blank']['blank_info']['addtime']
                    ];
                    break;
            }
            $list[] = $value;
        }
        $response = compact('list', 'is_over');

        return $response;
    }

    /**
     * 获取住友说通过内容ids
     * @param $params
     * @return array
     */
    public static function getlistByContentIds($params)
    {
        $all_id = $params['ids'];
        $page = $params['page'];
        $per_page = $params['per_page'];
        $uid = $params['uid'];
        $count = count($all_id);

        $current = $page * $per_page;

        //偏移量，当前页-1乘以每页显示条数
        $start = ($page - 1) * $per_page;
        //每页的wiki_id集合
        $ids = array_slice($all_id, $start, $per_page);

        $data['is_over'] = ($count <= $current) ? 1 : 0;
        $data['total'] = $count;

        $list = self::getFormatListByIds($ids, $uid);
        $data['list'] = array_values($list);

        return $data;
    }

    /**
     * 获取批量品牌住友说
     * @param array $params
     * @return array
     */
    public static function getListByBrandId(array $params)
    {
        $uid = $params['uid']; //用户id
        $brandId = $params['brand_id'];
        $page = $params['page'];
        $pageSize = $params['page_size'] ?? 20;
//        $currentTime = $params['current_time'];
        $sort = $params['sort'];


        //es搜索条件构造
        $esCondition = [
            'brand_id' => $brandId,
            'page' => $page,
            'page_size' => $pageSize,
            'is_owner' => false,
            'sort' => $sort,
            'filter_audit_status' => [
                mBrandContent::AUDIT_STATUS_REJECT,
            ],
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
            'filter_owner_uid' => self::FILTER_UIDS,
        ];

//        if ($currentTime != 0) {
//            $esCondition['current_time'] = $currentTime;
//        }
        // 是否置顶
        $rs = BrandEquityVerificationService::checkOneSourceStatus($brandId, SourceRightsInterface::TOP, true);
        if (!$rs) {
            $esCondition['is_top'] = 0;
        }

        //es搜索内容列表
        $info = \Doraemon\model\Elasticsearch\brandContent\BrandContentEs::search($esCondition['brand_id'], $esCondition);
//        $info = SearchSchedule::search(new \Biz\module\Classes\adm\ContentSearch($esCondition));
        $ids = $info['list'] ? array_column($info['list'], 'id') : [];
        $total = $info['total'] ?? 0;
        $is_over = $info['is_over'] ?? 1;

        $list = self::getFormatListByIds($ids, $uid, $brandId);
        $list = array_values($list);
        $response = compact('list', 'is_over');

        return $response;
    }

    public static function getFormatListByIds($ids, $uid, $brandId = 0)
    {
        //查询关联的内容列表
        $list = $ids ? mBrandContent::select('*', ['id' => $ids]) : [];
        $list = empty($list) ? [] : array_column($list, null, 'id');

        //查询关联的wiki
        $wikiWhere = WikiContentValid::validWikiCondition($ids);
        if ($brandId) {
            $wikiWhere['brand_id'] = $brandId;
        }
        $wiki = $ids ? \Biz\model\brand\ContentWiki::select('*', $wikiWhere) : [];

        $wikiMap = [];
        $wikiIds = [];
        foreach ($wiki as $v) {
            if (!isset($wikiMap[$v['cid']])) {
                $tempWikiId = $v['claim_wiki_id'] > 0 ? $v['claim_wiki_id'] : $v['wiki_id'];
                $wikiIds[] = $tempWikiId;
                $wikiMap[$v['cid']] = $tempWikiId;
            }
        }

        $wikiList = empty($wikiIds) ? [] : Wiki::getWikiList($wikiIds, $uid, Wiki::FIELDS_GROUP_BASE_LIST);

        $photoIds = [];
        $blankIds = [];
        foreach ($ids as $id) {
            if (isset($list[$id])) {
                $v = $list[$id];
                $objType = $v['obj_type'];
                $objId = $v['obj_id'];
                switch ($objType) {
                    case BlockType::TYPE_PHOTO:
                        $photoIds[] = $objId;
                        break;
                    case BlockType::TYPE_BLANK:
                        $blankIds[] = $objId;
                        break;
                }
            }
        }
        $photo_list = $photoIds ? HandleNote::handleNote($photoIds, HandleNote::MASONRY_LAYOUTS, $uid) : [];
        $blank_list = $blankIds ? HandleBlank::handleBlank($blankIds, HandleBlank::MASONRY_LAYOUTS, $uid) : [];

        $response = [];
        foreach ($ids as $id) {
            if (isset($list[$id])) {
                $v = $list[$id];
                $objType = $v['obj_type'];
                $objId = $v['obj_id'];
                $hitWiki = $wikiMap[$id] ?? 0;
                $temp = [];
                switch ($objType) {
                    case BlockType::TYPE_PHOTO:
                        if (isset($photo_list[$objId])) {
                            $temp = $photo_list[$objId];
                            $temp['photo']['wiki_list'] = [];
                            $wikiInfo = ($hitWiki && isset($wikiList[$hitWiki])) ? $wikiList[$hitWiki] : [];
                            if ($wikiInfo) {
                                $temp['photo']['wiki_list'][] = $wikiInfo;
                            }
                        }
                        break;
                    case BlockType::TYPE_BLANK:
                        if (isset($blank_list[$objId])) {
                            $temp = $blank_list[$objId];
                            $temp['blank']['wiki_list'] = [];
                            $wikiInfo = ($hitWiki && isset($wikiList[$hitWiki])) ? $wikiList[$hitWiki] : [];
                            if ($wikiInfo) {
                                $temp['blank']['wiki_list'][] = $wikiInfo;
                            }
                        }
                        break;
                }
                if (!empty($temp)) {
                    $response[$objId] = $temp;
                }
            }
        }
        return $response;
    }

    /**
     * app接口 住友说
     * @param $uid int 用户id
     * @param $brand_id int 品牌id
     * @param $sort string 排序
     * @param $page int 页码
     * @return array
     */
    public static function hhzPagedList($uid, $brand_id, $sort, $page)
    {
        //es搜索条件构造
        $esCondition = [
            'brand_id' => $brand_id,
            'page' => $page,
            'page_size' => 20,
            'is_owner' => false,
            'sort' => $sort,
            'filter_audit_status' => [
                mBrandContent::AUDIT_STATUS_REJECT,
            ],
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
            'filter_owner_uid' => self::FILTER_UIDS,

        ];
        // 是否置顶
        $rs = BrandEquityVerificationService::checkOneSourceStatus($brand_id, SourceRightsInterface::TOP, true);
        if (!$rs) {
            $esCondition['is_top'] = 0;
        } else {
            $esCondition['is_top'] = 1;
        }


        //es搜索内容列表
        $info = \Doraemon\model\Elasticsearch\brandContent\BrandContentEs::search($esCondition['brand_id'], $esCondition);
//        $info = SearchSchedule::search(new \Biz\module\Classes\adm\ContentSearch($esCondition));
        $ids = $info['list'] ? array_column($info['list'], 'id') : [];
        $total = $info['total'] ?? 0;
        $is_over = $info['is_over'] ?? 1;

        $formatedList = self::getFormatListByIds($ids, $uid, $brand_id);

        $list = [];
        foreach ($formatedList as $objId => $value) {
            $statSign = basicStatSign::genStatSign(basicStatSign::MODULE_BRAND_HOME_CHOSEN_CARD_LIST, [
                basicStatSign::EXTEND_KEY_OBJ_TYPE => $value['type'],
                basicStatSign::EXTEND_KEY_OBJ_ID => $objId,
                basicStatSign::EXTEND_KEY_PAGE => $page,
            ], ['brand_id' => $brand_id]);
            $wikiStatSign = basicStatSign::genStatSign(basicStatSign::MODULE_BRAND_HOME_CHOSEN_WIKI_CARD, [],
                ['brand_id' => $brand_id, 'relate_id' => $objId], false);
            switch ($value['type']) {
                case  BlockType::TYPE_PHOTO:
                    $value['photo']['wiki_list'] = $value['photo']['wiki_list'] ? \Doraemon\service\statSign\StatSignFormat::formatWikis($value['photo']['wiki_list'], $wikiStatSign) : [];
                    $value['photo']['wiki_list'] = \Doraemon\tools\StatSign::versionCompatible($value['photo']['wiki_list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');

                    $rightTopData['photo_info']['show_type'] = $value['photo']['photo_info']['show_type'];
                    $rightTopData['counter'] = $value['photo']['counter'];
                    $rightTopData['is_display_business'] = $value['photo']['photo_info']['is_display_business'];
                    $value['right_top'] = Link::iconFormat($rightTopData, Link::ICON_BUSINESS_NOTE);
                    unset($value['left_top']);

                    $value['action_info'] = [
                        'type' => 11,
                        'addtime' => $value['photo']['photo_info']['addtime']
                    ];
                    break;
                case  BlockType::TYPE_BLANK:
                    $value['blank']['wiki_list'] = $value['blank']['wiki_list'] ? \Doraemon\service\statSign\StatSignFormat::formatWikis($value['blank']['wiki_list'], $wikiStatSign) : [];
                    $value['blank']['wiki_list'] = \Doraemon\tools\StatSign::versionCompatible($value['blank']['wiki_list'], \Doraemon\tools\StatSign::WIKI_UP_GRADE_VERSION_522, BlockType::TYPE_WIKI, 'wiki');

                    $rightTopData['counter'] = $value['blank']['counter'];
                    $rightTopData['is_display_business'] = $value['blank']['blank_info']['is_display_business'];
                    $value['right_top'] = Link::iconFormat($rightTopData, Link::ICON_BUSINESS_BLANK);
                    unset($value['left_top']);

                    $value['action_info'] = [
                        'type' => 11,
                        'addtime' => $value['blank']['blank_info']['addtime']
                    ];
                    break;
            }
            $value['statSign'] = $statSign;
            $list[] = $value;
        }

        $response = compact('list', 'is_over');

        return $response;
    }

    /**
     * 从es获取content
     * @param $brand_id
     * @param $page
     * @param $tab
     * @param $toppedIds
     * @return array
     */
    public static function getEsContent($brand_id, $page, $tab, $toppedIds, $condition, $pageSize = 20): array
    {
        $params = [
            'tab' => $tab,
            'page' => $page,
            'per_page' => $pageSize,
            'fl' => $condition['fl'] ?? 'id',
            'obj_type' => $condition['obj_type'] ?? '',
            'publisher' => $condition['publisher'] ?? '',
            'addtime_s' => $condition['addtime_s'] ?? '',
            'addtime_e' => $condition['addtime_e'] ?? '',
            'claimtime_s' => $condition['claimtime_s'] ?? '',
            'claimtime_e' => $condition['claimtime_e'] ?? '',
            'wiki_id' => $condition['wiki_id'] ?? '',
            'wiki_title' => $condition['wiki_title'] ?? '',
            'word' => $condition['word'] ?? '',
        ];
        if ($tab == WikiContent::TAB_ALL) {
            $params['is_top'] = 1;
        }
        //获取查询列表 转用es搜索
        if ($tab != self::TAB_TOP) {
            $info = BrandContentEs::getManageList($brand_id, $params);
            $data['list'] = $info['list'] ?? [];
            $data['total'] = $info['total'] ?? 0;
            $data['is_over'] = $info['is_over'] ?? 1;
        } else {
            $list = [];
            foreach ($toppedIds as $id) {
                $list[] = ['id' => $id];
            }
            $data['list'] = $list;
            $data['total'] = count($toppedIds);
            $data['is_over'] = 1;
        }
        return $data;
    }

    /**
     * 内容管理列表
     * @param $uid
     * @param $tab
     * @param $brand_id
     * @param $condition
     * @param $page
     * @return array
     */
    public static function mangePagedList($uid, $tab, $brand_id, $condition, $page)
    {
        //被置顶的内容总数
        $toppedIds = $brand_id ? mBrandContent::getToppedIds($brand_id) : [];
        $toppedTotal = count($toppedIds);

        //待认领内容数量
        $waitTotal = BrandContentEs::getWaitClaimCount($brand_id);

        //es查询数据（在原有基础拆分出来的~因为我觉得太长了，逻辑可以咨询元武）
        $esData = self::getEsContent($brand_id, $page, $tab, $toppedIds, $condition);
        $ids = array_column($esData['list'], 'id');
        $total = $esData['total'];
        $is_over = $esData['is_over'];
        $debug = $esData['debug'] ?? null;
        //查询关联的内容列表
        $filter = [];
        if ($tab == self::TAB_CANCEL) {
            $filter['claim_content_status'] = [ContentWiki::RELATION_CANCEL]; //取消关联
        } else {
            $filter['claim_content_status'] = [ContentWiki::RELATION_DONE];   //已关联
        }
        //查询内容列表
        $list = $ids ? mBrandContent::select('*', ['id' => $ids] + $filter) : [];
        $list = $list ? array_column($list, null, 'id') : [];

        //查询关联的wiki
        $wikiWhere = [
            'cid' => $ids,
            'relation' => [
                ContentWiki::RELATION_DONE,//已关联
            ],
        ];
        $wiki = $ids ? ContentWiki::select('*', $wikiWhere) : [];

        $wikiMap = [];
        $wiki_ids = [];
        foreach ($wiki as $v) {
            if ($v['claim_wiki_id'] > 0) {
                $wiki_ids[$v['claim_wiki_id']] = $v['claim_wiki_id'];
            } else {
                $wiki_ids[$v['wiki_id']] = $v['wiki_id'];
            }
            $wikiMap[$v['cid']][] = $v;
        }

        //查询wiki标题和首图
        list('titleMap' => $titleMap, 'imgMap' => $imgMap, 'basicMap' => $basicMap, 'basic_id' => $basic_ids) = self::formatWikiList($wiki_ids);

        $response = [];
        $brandName = Brand::get('brand_name', ['id' => $brand_id]);

        $obj_ids = empty($list) ? [] : array_column(array_values($list), 'obj_id');

        $likes = $obj_ids ? sLike::isLikedMulti($uid, $obj_ids) : [];

        $likes = $likes ?? [];

        foreach ($ids as $id) {
            if (isset($list[$id])) {
                $v = $list[$id];
                $obj_type = $v['obj_type'];
                $obj_id = $v['obj_id'];
                $info = AdmContent::get($obj_type, $obj_id);
                $info = $info[$obj_id] ?? [];
                $tempWikiMap = $wikiMap[$v['id']] ?? [];
                $tempWikiMap = array_map(function ($v) use ($titleMap, $imgMap, $basicMap, $basic_ids) {
                    $tempWikiId = $v['claim_wiki_id'] ?: $v['wiki_id'];
                    $basic_id = $basicMap[$tempWikiId] ?? $tempWikiId;
                    if (in_array($basic_id, $basic_ids)) {
                        return [
                            'id' => $v['id'],
                            'basic_id' => $basic_id,
                            'wiki_id' => $tempWikiId,
                            'title' => $titleMap[$tempWikiId] ?? '',
                            'cover_img' => $imgMap[$tempWikiId] ?? '',
                        ];
                    }
                    return null;
                }, $tempWikiMap);

                // 可设置精选条件：必须是图片类型  并且 brand_uid>0 的并且未设置精选的内容 每天一次
                $can_selected = ($info['type_desc'] ?? '') == '图片' ? 1 : 0;
                if ($v['brand_uid'] > 0) {
                    $can_selected = 1;
                }
                $can_selected = $v['is_selected'] == 1 ? 0 : $can_selected;
                $response[] = [
                    'id' => $v['id'],
                    'obj_id' => $obj_id,
                    'obj_type' => $obj_type,
                    'audit_status' => $v['audit_status'],
                    'audit_desc' => mBrandContent::B_AUDIT_MAP[$v['audit_status']] ?? '',
                    'title' => $info['title'] ?? '',
                    'content' => $info['content'] ?? '',
                    'cover_pic_url' => $info['cover_pic_url'] ?? '',
                    'type_desc' => $info['type_desc'] ?? '',
                    'wiki_list' => array_values(array_filter($tempWikiMap)),
                    'claim_time' => date("Y.m.d", strtotime($v['claim_time'])),
                    'addtime' => date("Y.m.d", $info['addtime']),
                    //1 精选 0 普通 2当天禁用设置精选
                    'selected' => $v['is_selected'],
                    //1 可以被精选 0不支持被精选
                    'can_selected' => $can_selected,
                    'publisher' => $v['brand_uid'] > 0 ? $brandName : '住友',
                    'cancelable' => $v['brand_uid'] > 0,
                    'topped' => ($v['top_time'] > 0) ? 1 : 0,//1:置顶 0：未置顶
                    'link' => self::getAppLink($obj_id),
                    'is_like' => $likes[$obj_id] ?? 0
                ];
            }
        }
        $list = $response;

        return compact('waitTotal', 'toppedTotal', 'list', 'total', 'is_over', 'debug');
    }

    public static function waitClaimCondition($brand_id)
    {
        return [
            'brand_id' => $brand_id,
            'claim_content_status[!]' => mBrandContent::CLAIM_CONTENT_IGNORE,
            "OR" => [
                'wiki_status[>]' => 0,
                "AND" => [
                    'content_status' => mBrandContent::CLAIM_WAIT_MATCH,
                    'claim_content_status' => [
                        mBrandContent::CLAIM_CONTENT_NONE,
                        mBrandContent::CLAIM_CONTENT_MATCH,
                    ],
                ]
            ]
        ];
    }


    /**
     * 内容认领列表 422
     * @param $params
     * @return array
     */
    public static function waitClaimList($params)
    {
        $brand_id = $params['brand_id'];
        //用户领取数量
        $all_num = BrandContentEs::getWaitClaimCount($brand_id);

        if ($params['sort_type'] == BrandContentSearch::SORT_TYPE_AI) {
            $params['time_range'] = [
                'start' => time() - BrandContentSearch::SORT_TYPE_AI_ADDTIME_RANGE_MONTH,
                'end' => time(),
            ];
            $params['admin_score_range'] = [
                'min' => BrandContentSearch::SORT_TYPE_AI_ADMINSCORE_MIN,
                'max' => BrandContentSearch::SORT_TYPE_AI_ADMINSCORE_MAX,
            ];
        }
        $debug = BrandContentEs::getWaitClaimList($brand_id, $params);
        list("total" => $total, "is_over" => $is_over, "list" => $rows) = BrandContentEs::getWaitClaimList($brand_id, $params);

        if ($params['sort_type'] == BrandContentSearch::SORT_TYPE_AI && $params['page'] == 1 && empty($rows)) {
            $params['time_range'] = [
                'start' => time() - BrandContentSearch::SORT_TYPE_AI_ADDTIME_RANGE_YEAR,
                'end' => time(),
            ];
            list("total" => $total, "is_over" => $is_over, "list" => $rows) = BrandContentEs::getWaitClaimList($brand_id, $params);
        }

        $uids = array_column($rows, 'owner_uid');
        if ($uids) {
            $user_infos = User::getBatchBasicUserInfo($uids);
            $user_infos = empty($user_infos) ? [] : array_column($user_infos, null, 'uid');
            foreach ($rows as &$v) {
                $v['user_info'] = $user_infos[$v['owner_uid']] ?? null;
            }
        }

        $ids = array_column($rows, 'id');
        $rows = array_column($rows, null, 'id');
        $list = empty($ids) ? [] : mBrandContent::select('*', ['id' => $ids]);
        $list = empty($list) ? [] : array_column($list, null, 'id');
        $cid = array_keys($list);

        $wiki = [];
        if ($cid) {
            //查询关联的wiki
            $wikiWhere = [
                'brand_id' => $brand_id,
                'relation' => [
                    \Biz\model\brand\ContentWiki::RELATION_MATCH,
                ],
                'cid' => $cid
            ];
            $wiki = \Biz\model\brand\ContentWiki::select('*', $wikiWhere);
        }
        $wikiMap = [];
        $wiki_ids = [];
        if ($wiki) {
            foreach ($wiki as $v) {
                $wiki_ids[$v['wiki_id']] = $v['wiki_id'];
                $wikiMap[$v['cid']][] = $v;
            }
        }

        //查询wiki标题和首图
        list('titleMap' => $titleMap) = self::formatWikiList($wiki_ids);

        $obj_ids = empty($list) ? [] : array_column(array_values($list), 'obj_id');

        $likes = sLike::isLikedMulti($params['uid'], $obj_ids);

        $likes = $likes ?? [];

        //点赞数、评论、收藏数
        $photoIds = $blankIds = $articleIds = $answerIds = [];
        foreach ($obj_ids as $obj_id) {
            $type = IdParse::getType($obj_id);
            switch ($type) {
                case BlockType::TYPE_BLANK:
                    $blankIds[] = $obj_id;
                    break;
                case BlockType::TYPE_ARTICLE:
                    $articleIds[] = $obj_id;
                    break;
                case BlockType::TYPE_PHOTO:
                    $photoIds[] = $obj_id;
                    break;
                case BlockType::TYPE_ANSWER:
                    $photoIds[] = $obj_id;
                    $answerIds[] = $obj_id;
                    break;
            }
        }

        $photoCounters = empty($photoIds) ? [] : PhotoCounter::getMulti($photoIds);

        $blankCounters = empty($blankIds) ? [] : BlankCounter::getMulti($blankIds);

        $articleCounters = empty($articleIds) ? [] : ArticleCounter::getMulti($articleIds);

        $answerCounters = empty($answerIds) ? [] : AnswerCounter::getCounterMulti($answerIds);

        $counterTypeMap = [
            BlockType::TYPE_BLANK => $blankCounters,
            BlockType::TYPE_ARTICLE => $articleCounters,
            BlockType::TYPE_PHOTO => $photoCounters,
            BlockType::TYPE_ANSWER => $photoCounters,
        ];

        $response = [];
        foreach ($ids as $id) {
            $v = $list[$id] ?? [];
            $esData = $rows[$id] ?? [];
            if (empty($v)) {
                continue;
            }
            $wikiCheck = $v['wiki_status'] > 0;
            $contentCheck = ($v['content_status'] == mBrandContent::CLAIM_WAIT_MATCH) && in_array($v['claim_content_status'],
                    [
                        mBrandContent::CLAIM_CONTENT_NONE,
                        mBrandContent::CLAIM_CONTENT_MATCH,
                    ]);
            if (!($wikiCheck || $contentCheck)) {
                continue;
            }
            $obj_type = $v['obj_type'];
            $obj_id = $v['obj_id'];
            $info = AdmContent::get($obj_type, $obj_id);
            $info = $info[$obj_id] ?? [];
            $tempWikiMap = $wikiMap[$v['id']] ?? [];
            $tempWikiMap = array_map(function ($v) use ($titleMap) {
                return [
                    'id' => $v['id'],
                    'wiki_id' => $v['wiki_id'],
                    'title' => $titleMap[$v['wiki_id']] ?? '',
                ];
            }, $tempWikiMap);
            $count = count($tempWikiMap);
            $template = $v['claim_content_status'] == mBrandContent::CLAIM_CONTENT_DONE ?
                "此内容已收录，另检索到有 %d 个与你有关的商品" : "此内容关联了 %d 个与你有关的商品";
            $words = json_decode($v['words']);
            $tagWords = $words->tag ?? [];
            $words = $words->content ?? [];
            $keywords = $words->search_keywords ?? [];
            $words = array_merge($words, $tagWords, $keywords);
            $words = array_flip(array_flip($words));
            $words = array_values($words);
            $search_type = $v['search_type'] ? explode(',', $v['search_type']) : [];
            $reason = $search_type[0];
            //领取类型 1：仅支持「认领并关联商品」，不可「仅认领内容」
            $receive_type = 0;
            if (BrandContentKeywords::SEARCH_TYPE_KEYWORDS === (int)$reason) {
                $receive_type = 1;
            }

            $objCount = isset($counterTypeMap[$obj_type]) ? ($counterTypeMap[$obj_type][$obj_id] ?? null) : null;

            if (IdParse::getType($obj_id) == BlockType::TYPE_ANSWER && $objCount) {
                $objCount['comments'] = isset($answerCounters[$obj_id]) ? $answerCounters[$obj_id]['comments'] : $objCount['comments'];
            }

            $response[] = [
                'id' => $v['id'],
                'obj_id' => $obj_id,
                'obj_type' => $obj_type,
                'title' => $info['title'] ?? '',
                'content' => $info['content'] ?? '',
                'cover_pic_url' => $info['cover_pic_url'] ?? '',
                'type_desc' => $info['type_desc'] ?? '',
                'wiki_list' => $tempWikiMap,
                'like' => isset($objCount) ? ($objCount['like'] ?? 0) : 0,
                'favorite' => isset($objCount) ? ($objCount['favorite'] ?? 0) : 0,
                'fans' => $esData['fans'] ?? 0,
                'comment' => isset($objCount) ? ($objCount['comments'] ?? 0) : 0,
                'user_info' => $esData['user_info'],
                'key_words' => $words,
                'desc' => $count ? vsprintf($template, [$count]) : '',
                'link' => self::getAppLink($v['obj_id']),
                'receive_type' => $receive_type,
                'add_time' => $info['addtime'],
                'is_like' => $likes[$obj_id] ?? 0,
                'is_recommend' => ($esData['admin_score'] ?? 0) >=  BrandContentSearch::SORT_TYPE_AI_ADMINSCORE_MIN,
            ];
        }
        $list = $response;

        if ($total > 10000) {
            $total = 10000;  //es深度分页问题
            $is_over = 1;
        }

        return compact('total', 'all_num', 'list', 'is_over', 'debug');
    }


    /**
     * 获取app二维码连接
     * @param $obj_id
     * @return false|string
     */
    public static function getAppLink($obj_id)
    {
        $data['type'] = 'link';
        $data['link'] = self::generateLink($obj_id);
        return json_encode($data);
    }

    /**
     * 取消商品关联
     * @param $id int 内容关联wiki的记录id
     * @param $brand_id int 品牌id
     * @param $uid int 品牌用户id
     * @param bool $flag
     */
    public static function cancelWiki($id, $brand_id, $uid, $flag = true)
    {
        //检查取消商品的是否满足条件
        $wiki = WikiContentValid::cancelWiki($id, $brand_id);

        //检查忽略的内容是否满足条件
        $content = WikiContentValid::cancelWikiContent($wiki['cid'], $brand_id);

        mBrandContent::action(function () use ($brand_id, $uid, $id, $wiki, $content) {
            $data = [
                'relation' => \Biz\model\brand\ContentWiki::RELATION_CANCEL,
                'claim_wiki_id' => 0,
            ];

            $where = [
                'id' => $id,
            ];

            //如果是追加的商品,需要取消与内容的关联
            if ($wiki['operation_mode'] & \Biz\model\brand\ContentWiki::OPERATION_MODE_EXTEND) {
                $info = AdmContent::get($wiki['obj_type'], $wiki['obj_id']);
                $info = $info[$wiki['obj_id']] ?? [];
                $obj_uid = $info['uid'] ?? 0;
                $cancelWikiId = $wiki['claim_wiki_id'] ?: $wiki['wiki_id'];

                $wikiType = [
                    0 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_NOTE,
                    1 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_ARTICLE,
                    5 => \Biz\model\wiki\ObjRelateWiki::OBJ_TYPE_BLANK,
                ];
                \Biz\module\Classes\wiki\RelateWiki::delRelateWiki(
                    $obj_uid,
                    $wiki['obj_id'],
                    $wikiType[$wiki['obj_type']],
                    null,
                    null,
                    $cancelWikiId,
                    \Biz\model\wiki\ObjRelateWiki::TYPE_BRAND_REL
                );
            }

            //如果是认领的商品,需要取消品牌的关联
            if ($wiki['operation_mode'] & \Biz\model\brand\ContentWiki::OPERATION_MODE_CLAIM) {
                //查询绑定wiki的basic_id
                $basicId = \Biz\model\wiki\Wiki::get('basic_id', ['id' => $wiki['wiki_id']]);
                //解除wiki的关联关系
                WikiBasic::setBrandWikiBasic($brand_id, $wiki['wiki_id'], $basicId, false);
            }

            //变更商品关联状态
            $rs = \Biz\model\brand\ContentWiki::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('修改内容记录失败');
            }

            //确认取消关联后若该内容无其他关联商品，则需判断内容本身是否命中一级品牌词，若否，则需从品牌内容池删除该内容数据，若是则保留。
            $self = $content['brand_uid'] > 0;
            $contentNoneMatch = $content['content_status'] == mBrandContent::CLAIM_NONE_MATCH;
            $wikiCount = $content['wiki_status'] + $content['wiki_num'] <= 1;

            $contentData = ['wiki_num[-]' => 1];
            if ($contentNoneMatch && !$self && $wikiCount) {
                $contentData['claim_content_status'] = mBrandContent::CLAIM_CONTENT_NONE;
            }
            if ($content['wiki_num'] == 1) {
                $contentData['match_status'] = $content['match_status'] & ~mBrandContent::MATCH_BRAND_WIKI;
            }

            $rs = mBrandContent::update($contentData, ['id' => $content['id']])->rowCount();
            if (!$rs) {
                throw new \Exception('更新认领状态失败');
            }

            //添加操作日志
            self::addDebugTrace($brand_id, $content['obj_id'], [
                'title' => '取消内容认领状态',
                'contentData' => $contentData,
                'id' => $content['id']
            ], $uid);

            //添加操作日志
            self::addDebugTrace($brand_id, $content['obj_id'], [
                'title' => '取消商品关联',
                'data' => $data,
                'where' => $where
            ], $uid);
        });

        if ($flag) {
            self::afterCancelWiki($brand_id, $uid, $wiki['wiki_id'], $wiki['claim_wiki_id'], $id);
        }
    }

    public static function afterCancelWiki($brand_id, $uid, $wiki_id, $claim_wiki_id, $id)
    {
        //查询拥有相同商品的关联
        $searchCondition = [
            'brand_id' => $brand_id,
            'wiki_id' => $wiki_id,
            'claim_wiki_id' => $claim_wiki_id,
            'id[!]' => $id,
            'audit_status' => mBrandContent::AUDIT_STATUS_SUCCESS,
            'relation' => \Biz\model\brand\ContentWiki::RELATION_DONE
        ];
        $list = \Biz\model\brand\ContentWiki::select('*', $searchCondition);
        if (empty($list)) {
            return;
        }

        foreach ($list as $wiki) {
            try {

                self::cancelWiki($wiki['id'], $brand_id, $uid, false);

            } catch (\Exception $e) {
                //错误日志
                $title = '相同商品的取消关联';
                self::addDebugTrace($brand_id, '', compact('title', 'wiki', 'e'));
            }
        }
    }

    public static function cancel($id, $brand_id, $uid)
    {
        //检查内容是否满足条件
        WikiContentValid::cancelContent($id, $brand_id);

        $data = [
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_CANCEL,
            'top_time' => 0
        ];

        $where = [
            'id' => $id,
        ];

        mBrandContent::action(function () use ($brand_id, $uid, $data, $where) {
            //添加忽略内容记录
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('修改内容记录失败');
            }

            //添加操作日志
            self::addDebugTrace($brand_id, '', [
                'title' => '取消收录的内容',
                'data' => $data,
                'where' => $where
            ], $uid);
        });
    }

    /**
     * 删除收录内容
     * @param $obj_id
     */
    public static function delClaim($obj_id)
    {
        //更改认领状态
        $obj_type = \Doraemon\pockets\IdSender\IdSender::getType($obj_id);

        $where = [
            'obj_type' => $obj_type,
            'obj_id' => $obj_id,
        ];

        $data = [
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_NONE,
            'content_status' => mBrandContent::CLAIM_NONE_MATCH,
            'wiki_status' => 0,
            'claim_type' => mBrandContent::CLAIM_TYPE_NONE,
            'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
        ];

        if (mBrandContent::count($where)) {

            mBrandContent::update($data, $where);

            //添加操作日志
            self::addTrace('删除收录内容', 0, $obj_id, mBrandContent::log());
        }
    }

    /**
     * 仅认领内容
     * @param $id
     * @param $brand_id
     * @param $uid
     * @param string $rightsName
     * @throws \Exception
     */
    public static function claim($id, $brand_id, $uid, $rightsName = '')
    {
        $content = mBrandContent::get('*', [
            'brand_id' => $brand_id,
            'id' => $id,
        ]);

        //仅命中「内容检索词」进入待认领列表的内容仅支持「认领并关联商品」，不可「仅认领内容」
        $search_type = explode(',', $content['search_type']) ?? [];
        if (count($search_type) == 1) {
            $reason = $search_type[0] ?? 0;
            if (BrandContentKeywords::SEARCH_TYPE_KEYWORDS === (int)$reason) {
                throw new \Exception('非法操作，仅支持认领并关联商品');
            }
        }

        if (!$content) {
            throw new \Exception('操作的记录不存在');
        }

        $allowStatus = [
            mBrandContent::CLAIM_CONTENT_NONE,
            mBrandContent::CLAIM_CONTENT_MATCH,
        ];
        if (!in_array($content['claim_content_status'], $allowStatus)) {
            throw new \Exception('操作记录的状态不正确');
        }

        $data = [
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_DONE,
            'content_status' => mBrandContent::CLAIM_MATCH,
            'claim_type' => mBrandContent::CLAIM_TYPE_CONTENT_ONLY,
            'audit_status' => mBrandContent::AUDIT_STATUS_NONE,
            'claim_time' => date("Y-m-d H:i:s")
        ];

        if ($content['first_claim_time'] == '0000-00-00 00:00:00') {
            $data['first_claim_time'] = date("Y-m-d H:i:s");
        }

        $where = [
            'id' => $id,
        ];

        //添加忽略内容记录
        $rs = mBrandContent::update($data, $where)->rowCount();
        if (!$rs) {
            throw new \Exception('添加忽略内容记录失败');
        }

        return $content;
    }

    /**
     * 忽略内容认领
     * @param $id
     * @param $brand_id
     * @param $uid
     * @throws \Exception
     */
    public static function ignore($id, $brand_id, $uid)
    {
        //检查忽略的内容是否满足条件
        WikiContentValid::ignoreContent($id, $brand_id);

        $data = [
            'claim_content_status' => mBrandContent::CLAIM_CONTENT_IGNORE,
            'content_status' => mBrandContent::CLAIM_NONE_MATCH,
        ];

        $where = [
            'id' => $id,
        ];

        mBrandContent::action(function () use ($brand_id, $data, $where, $uid) {
            //添加忽略内容记录
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('添加忽略内容记录失败');
            }

            //添加操作日志
            self::addDebugTrace($brand_id, '', [
                'title' => '忽略内容认领',
                'data' => $data,
                'where' => $where
            ], $uid);
        });

    }

    /**
     * 忽略内容中的wiki
     * @param $id
     * @param $wid
     * @param $brand_id
     * @param $uid
     * @throws \Exception
     */
    public static function ignoreWiki($id, $wid, $brand_id, $uid)
    {
        //检查忽略的内容是否满足条件
        $content = WikiContentValid::ignoreWikiContent($id, $brand_id);

        //检查忽略的商品是否满足条件
        $wiki = WikiContentValid::ignoreWiki($wid, $brand_id);


        $data = [
            'relation' => \Biz\model\brand\ContentWiki::RELATION_IGNORE,
        ];

        $where = [
            'id' => $wiki['id'],
        ];

        mBrandContent::action(function () use ($brand_id, $data, $where, $uid, $content, $wiki) {
            //关联wiki的状态改为忽略
            $rs = \Biz\model\brand\ContentWiki::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('忽略商品失败');
            }

            //待认领商品数量-1
            if ($content['wiki_status'] == 1) {
                $upData = [
                    'wiki_status[-]' => 1,
                    'match_status' => $content['match_status'] & ~mBrandContent::MATCH_WIKI_TITLE
                ];
            } else {
                $upData = ['wiki_status[-]' => 1];
            }
            $rs = mBrandContent::update($upData, ['id' => $content['id']])->rowCount();
            if (!$rs) {
                throw new \Exception('更新待认领商品数量失败');
            }

            //添加忽略wiki记录
            $record = [
                'brand_id' => $brand_id,
                'op_type' => \Biz\model\brand\ContentIgnore::OP_TYPE_WIKI,
                'op_id' => $wiki['wiki_id'],
                'content_status' => \Biz\model\brand\ContentIgnore::STATUS_NORMAL,
            ];
            $rs = \Biz\model\brand\ContentIgnore::insert($record)->rowCount();

            if (!$rs) {
                throw new \Exception('添加[忽略wiki记录]失败');
            }

            //添加操作日志
            self::addDebugTrace($brand_id, '', [
                'title' => '忽略商品认领',
                'data' => $data,
                'where' => $where
            ], $uid);

        });

    }

    /**
     * 记录品牌操作日志
     * @param $operate
     * @param $brand_id
     * @param $obj_id
     * @param $operate_log
     * @param $uid
     * @param $aid
     */
    public static function addTrace($operate, $brand_id, $obj_id = '', $operate_log = '', $uid = 0, $aid = 0)
    {
        $data = [
            'brand_id' => intval($brand_id),
            //商家品牌id
            'operate' => $operate,
            //内容id
            'obj_id' => $obj_id,
            //操作类型
            'operate_uid' => $uid,
            //用户uid
            'operate_aid' => $aid,
            //管理员uid
            'operate_log' => is_string($operate_log) ? $operate_log : json_encode($operate_log, JSON_UNESCAPED_UNICODE),
            //操作描述
            'addtime' => date("Y-m-d H:i:s")
        ];

//        ContentTrace::insert($data)->rowCount();

    }

    //添加品牌与内容的关联关系
    public static function saveBrandContent($data)
    {
        $id = $data['id'] ?? 0;
        if ($id) {
            $where = ['id' => $id];
            $rs = mBrandContent::update($data, $where)->rowCount();
            if (!$rs) {
                throw new \Exception('添加自动收录记录失败');
            }

        } else {
            $data['addtime'] = date("Y-m-d H:i:s");
            //添加品牌与内容的关联关系
            $rs = mBrandContent::insert($data)->rowCount();
            if (!$rs) {
                throw new \Exception('添加自动收录记录失败');
            }
        }

    }


    public static function addDebugTrace($brand_id, $obj_id, $params, $uid = 0, $aid = 0)
    {
        if (self::$debug) {
            Log::position_info('品牌认领debug', compact('brand_id', 'obj_id', 'params', 'uid', 'aid'));
        }

        return true;
    }


    public function getWikiList($obj_id, $brand_id)
    {
        $relations = mBrandContent::getAllByBidAndOid($obj_id, $brand_id);
        $cids = [];
        $wikiList = [];
        if ($relations && is_array($relations)) {
            $cids = (array)array_column($relations, 'id');
        }
        $wiki_ids = \Biz\model\brand\ContentWiki::getByOIdBidCids($brand_id, $obj_id, $cids);
        $basic_id = $wiki_ids ? \Biz\model\wiki\Wiki::select('basic_id', ['id' => $wiki_ids]) : [];
        if ($basic_id) {
            $wikiList = \Biz\model\wiki\Wiki::selectByWhere([
                'is_default' => 1,
                'basic_id' => $basic_id,
                'brand_id' => $brand_id,
                'status[!]' => \Biz\model\wiki\Wiki::STATUS_DEL
            ]);
        }
        $imgs = array_filter(array_column($wikiList, 'cover_img'));
        $imgs = array_values($imgs);
        $imgs = array_slice($imgs, 0, 2);
        return (array)$imgs;
    }

    public static function sendMsg($uid, $msg = '', $obj_id = null)
    {
        // 发送下行消息
        if ($uid <= 0) {
            return;
        }

        // 生成app链接
        $link = self::generateLink($obj_id);

        $message_data = [
            'msgCode' => 0,
            'to_uid' => $uid,
            'msgParams' => [
                'from_uid' => \Doraemon\service\User::DEFAULT_HAOHAOZHU_UID,
                'title' => '',
                'link' => $link,
                'detail' => $msg,
            ],
        ];
        \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send', $message_data, \Doraemon\cache\Queue::QUEUE_DORAEMON);
    }

    /**
     * 保存或更新
     * @param $data
     * @param $where
     * @return array
     */
    public static function saveWords($data, $where)
    {
        $res = BrandContentKeywords::updateOrCreate($where, $data);
        if ($res) {
            $msg['msg'] = '添加成功';
        } else {
            $msg['msg'] = '已存在！,请查看';
        }
        return $msg;
    }

    /**
     * 获取检索词列表
     * @param $brand_id
     * @return array|mixed
     */
    public static function getBrandInfo($brand_id)
    {
        return Brand::getByWhere(['id' => $brand_id], ['brand_name', 'brand_alias']);
    }

    /**
     * 获取字段信息
     * @param $brand_id
     * @return array|false|string[]
     */
    public static function getWords($brand_id)
    {
        $where['brand_id'] = $brand_id;
        return BrandContentKeywords::first($where, ['search_keywords', 'new_keywords']);
    }
}
